package com.bb.blog.code.mq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class RabbitMqExample3 {

    private static final String TASK_QUEUE_NAME = "task_queue3";
    private static final String EXCHANGE_NAME = "exchange_3";
    static class Prod{
        public static void main(String[] args) throws IOException, TimeoutException {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("localhost");
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            channel.queueDeclare(TASK_QUEUE_NAME,true,false,false,null);
            channel.exchangeDeclare(EXCHANGE_NAME,"fanout");
            String message = "taskqueue";
            int i = 1000000;
            for (; ; i++) {
                String msg = message+i;
                channel.basicPublish(EXCHANGE_NAME,"", MessageProperties.TEXT_PLAIN,msg.getBytes(StandardCharsets.UTF_8));
                System.out.println("send " + msg);

            }


        }
    }


    static class Consumer{
        public static void main(String[] argv) throws Exception {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
            //定义一个匿名额队列
            String queueName = channel.queueDeclare().getQueue();
            //将队列和交换机绑定
            channel.queueBind(queueName, EXCHANGE_NAME, "");

            System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            };
            channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
        }

    }
}
